<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Model;

//脑筋急转弯
class BraintwisterController extends CommonController {

    public function index(){
        self::user_list();
    }

    //用户模块
    public function user_list()
    {

        $User  =   M('wxusers');

        $where['appid'] = "wxbcb264959c7f8ffe"; //脑力王者赛

        $count      = $User->where($where)->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,50);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $data['user_list'] = $User->where($where)->order('wxusers_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('page',$show);// 赋值分页输出

        $this->assign("data",$data);
        $this->display('user_list');
    }


    //好友
    public function frend_ranking(){

        $wxuserid = I('get.wxusers_id','','int');
        $where['uid'] = $wxuserid;

        if (empty($wxuserid))
        {
            $this->error('非法请求');
        }

        $coupling_uids = M('WxusersRelationship')->where($where)->getField('coupling_uid',true);

        if (empty($coupling_uids)){
            $coupling_uids = array();
        }

        $coupling_uids[] = $wxuserid;

        $uids = array();
        $uids = M('WxusersRelationship')->where(array('coupling_uid'=>$wxuserid))->getField('uid',true);
        if (empty($uids)){
            $uids = array();
        }

        $ids = array_unique(array_merge($coupling_uids,$uids));//合并去重

        $where1['wxusers_id'] = array('in',$ids);
        $user = "";
        if ($ids){
            $user = M('Wxusers')->field('wxusers_id,nickName,avatarUrl,checkpoint_final')->where($where1)->limit(100)->order('checkpoint_final desc')->select();
        }

        $this->assign('data',$user);
        $this->display('frend_ranking');

    }

    //更多好玩
    public function game_more()
    {
        $data['game_list']  =   M('appshow')->select();
        $this->assign("data",$data);
        $this->display('game_more');
    }

    public function send(){

        if (IS_AJAX)
        {
            $app = I('post.app','','htmlspecialchars');
            $tem = I('post.tem','','htmlspecialchars');
            $keyword1 = I('post.keyword1','','htmlspecialchars');
            $keyword2 = I('post.keyword2','','htmlspecialchars');
            $keyword3 = I('post.keyword3','','htmlspecialchars');
            $keyword4 = I('post.keyword4','','htmlspecialchars');
            $keyword5 = I('post.keyword5','','htmlspecialchars');
            $emphasis_keyword = I('post.emphasis_keyword','','htmlspecialchars');
            $touser = I('post.touser','','htmlspecialchars');
            $uid = I('post.uid','','int');

            if ($uid){
                $touser = M('wxusers')->where('wxusers_id='.$uid)->getField('openId');
            }

            if ($app=='1'){ //脑力王者
                $appid = "wxbcb264959c7f8ffe";
                $secret = "e5400b4ebeba664cb0427e8f05cd8259";

            }elseif($app=='2'){ //脑经大转弯
                $appid = "wx2faae9d47390a9e7";
                $secret = "ef9b7ee6ca62bc4aaf856a5dd8420388";
            }

            $data = array();
            if ($keyword1){
                $data['keyword1'] = array(
                    'value'=>$keyword1,
                    'color'=>'#173177',
                );
            }

            if ($keyword2){
                $data['keyword2'] = array(
                    'value'=>$keyword2,
                    'color'=>'#173177',
                );
            }

            if ($keyword3){
                $data['keyword3'] = array(
                    'value'=>$keyword3,
                    'color'=>'#173177',
                );
            }

            if ($keyword4){
                $data['keyword4'] = array(
                    'value'=>$keyword4,
                    'color'=>'#173177',
                );
            }

            if ($keyword5){
                $data['keyword5'] = array(
                    'value'=>$keyword5,
                    'color'=>'#173177',
                );
            }

            $res = $this->sendnaojin($appid,$secret,$tem,$data,$emphasis_keyword,$touser);

            if (!empty($res))
            {
                $msg['state']   =   200;
                $msg['error']   =   '发送成功';
                $this->ajaxReturn ($msg,'JSON');
            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '发送失败';
                $this->ajaxReturn ($msg,'JSON');
            }


        }
        $this->display('send');


    }

    /**
     * 缓存到文件
     */
    private function cachebraint($appid){

        $list = S('admincachebraint');

        if (!empty($list)){
            return $list;
        }


        $where2['appid'] = $appid;
        $where2['status'] = '-1';

        $info = M('wxopen_template_send')->field('wxopen_template_send_id,appid,touser,template_id,page,form_id')->where($where2)->order('wxopen_template_send_id asc')->select();

        $data = array();
        foreach ($info as $key=>$value){

            $data[$value['touser']] = $value;

        }

        S('admincachebraint',$data,7200*24*10);
        $list = S('admincachebraint');
        return $list;

    }


    /**
     * 脑筋
     * @return int
     */
    private function sendnaojin($appid,$secret,$template_id,$fdata,$emphasis_keyword,$touser){


        if ($touser){
            $where2['appid'] = $appid;
            $where2['status'] = '-1';
            $where2['touser'] = $touser;
            $info = M('wxopen_template_send')->field('wxopen_template_send_id,appid,touser,template_id,page,form_id')->where($where2)->limit(1)->order('wxopen_template_send_id desc')->select();
        }else{
            $info = $this->cachebraint($appid);
        }

       $access_token = $this->gettoken($appid,$secret);

        foreach ($info as $key=>$value){


            $data = array(
                'touser'=>$value['touser'],
                'template_id'=>$template_id,
                'page'=>'pages/index/index',
                'form_id'=>$value['form_id'],
                'data'=>$fdata,
                'emphasis_keyword'=>$emphasis_keyword
            );
            $res = $this->sendtemp($access_token,$data);
            $save = array(
                'errcode'=>$res['errcode'],
                'errmsg'=>$res['errmsg'],
                'data'=>json_encode($data['data']),
                'emphasis_keyword'=>$data['emphasis_keyword'],
            );


            if ($res['errcode']==0){
                $save['status'] = 1;
               // M('wxopen_template_send')->where(array('wxopen_template_send_id'=>$value['wxopen_template_send_id']))->save($save);
            }else{
                $save['status'] = 2;
               // M('wxopen_template_send')->where(array('wxopen_template_send_id'=>$value['wxopen_template_send_id']))->save($save);
            }

        }

        return 1;

    }


    /**
     * 发送模板消息
     */
    private function sendtemp($access_token,$data){

        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

        $res = $this->getcomponent($url,json_encode($data,true));

        return $res;

    }



    public function game_more_add()
    {
        if (IS_AJAX)
        {
            $data['appid']     =   I('post.appid','','htmlspecialchars');
            $data['url']       =   I('post.url','','htmlspecialchars');
            $data['envVersion']=   I('post.envversion','','htmlspecialchars');
            $data['logo']      =   I('post.logo','','htmlspecialchars');
            $data['content']   =   I('post.content','','htmlspecialchars');
            $data['isshow']    =   I('post.isshow','','htmlspecialchars');
            $data['title']     =   I('post.title','','htmlspecialchars');

            $result     =   M('appshow')->data($data)->add(); // 根据条件更新记录

            //记录相关操作日志

            if (!empty($result))
            {
                $msg['state']   =   200;
                $msg['error']   =   '添加成功';
                $this->ajaxReturn ($msg,'JSON');
            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '添加失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }
        else
        {
            $this->display('game_more_add');
        }
    }

    public function game_more_edit()
    {
        if (IS_AJAX)
        {
            $where['appshow_id']  =   I('post.appshow_id','','htmlspecialchars');
            if (empty($where['appshow_id']))
            {
                $msg['state']   =   -1;
                $msg['error']   =   '非法请求';
                $this->ajaxReturn ($msg,'JSON');
            }

            $data['appid']     =   I('post.appid','','htmlspecialchars');
            $data['url']       =   I('post.url','','htmlspecialchars');
            $data['envVersion']=   I('post.envversion','','htmlspecialchars');
            $data['logo']      =   I('post.logo','','htmlspecialchars');
            $data['content']   =   I('post.content','','htmlspecialchars');
            $data['isshow']    =   I('post.isshow','','htmlspecialchars');
            $data['title']     =   I('post.title','','htmlspecialchars');

            $result     =   M('appshow')->where($where)->save($data); // 根据条件更新记录

            //记录相关操作日志

            if (!empty($result))
            {
                $msg['state']   =   200;
                $msg['error']   =   '更新成功';
                $this->ajaxReturn ($msg,'JSON');
            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '更新失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }
        else
        {
            $where['appshow_id']  =   I('get.id','','htmlspecialchars');

            if (empty($where['appshow_id']))
            {
                $this->error('非法请求');
            }

            $field      =   array('appshow_id','appid','url','envVersion','logo','content','isshow','title');
            $data['game_info']  =   M('appshow')->where($where)->field($field)->find();

            if ( empty($data))
            {
                $this->error('数据不存在');
            }

            $this->assign("data",$data);
            $this->display('game_more_edit');
        }
    }

    //游戏题库
    public function game_question()
    {
        $field                  =   array('quersion_id','answer','img_src','confusingdata','sort','createtime','updatetime','appid');
        $data['game_question']  =   M('quersion')->order('quersion_id desc')->field($field)->select();
        $this->assign("data",$data);
        $this->display('game_question');
    }

    public function game_question_edit()
    {
        if (IS_AJAX)
        {
            $where['quersion_id']  =   I('post.quersion_id','','htmlspecialchars');
            if (empty($where['quersion_id']))
            {
                $msg['state']   =   -1;
                $msg['error']   =   '非法请求';
                $this->ajaxReturn ($msg,'JSON');
            }

            $data['answer']             =   I('post.answer','','htmlspecialchars');
            $data['img_src']            =   I('post.img_src','','htmlspecialchars');
            $data['sort']               =   I('post.sort','','htmlspecialchars');
            $data['confusingdata']      =   I('post.confusingdata','','htmlspecialchars');
            $data['sort']               =   I('post.sort','','htmlspecialchars');

            $result     =   M('quersion')->where($where)->save($data); // 根据条件更新记录

            //记录相关操作日志

            if (!empty($result))
            {
                $msg['state']   =   200;
                $msg['error']   =   '更新成功';
                $this->ajaxReturn ($msg,'JSON');
            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '更新失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }
        else
        {
            $where['quersion_id']  =   I('get.id','','htmlspecialchars');

            if (empty($where['quersion_id']))
            {
                $this->error('非法请求');
            }

            $field                  =   array('quersion_id','answer','img_src','confusingdata','sort','createtime','updatetime','appid');
            $data['game_question']  =   M('quersion')->where($where)->field($field)->find();

            if ( empty($data))
            {
                $this->error('数据不存在');
            }

            $this->assign("data",$data);
            $this->display('game_question_edit');
        }
    }

    public function game_question_add()
    {
        if (IS_AJAX)
        {
            $data['answer']             =   I('post.answer','','htmlspecialchars');
            $data['img_src']            =   I('post.img_src','','htmlspecialchars');
            $data['sort']               =   I('post.sort','','htmlspecialchars');
            $data['confusingdata']      =   I('post.confusingdata','','htmlspecialchars');
            $data['sort']               =   I('post.sort','','htmlspecialchars');

            $result     =   M('quersion')->data($data)->add(); // 根据条件更新记录

            //记录相关操作日志

            if (!empty($result))
            {
                $msg['state']   =   200;
                $msg['error']   =   '添加成功';
                $this->ajaxReturn ($msg,'JSON');
            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '添加失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }
        else
        {
            $this->display('game_question_add');
        }
    }

    //排行榜
    public function week_ranking()
    {
        $field                  =   array('challenge_week_id','year','challenge_week','wxusers_id','checkpoint_final','createtime','exittime','passnum','appid');
        $data['week_ranking']   =   M('challenge_week')->where($where)->field($field)->select();
        $this->assign("data",$data);
        $this->display('week_ranking');
    }

    //挑战记录
    public function game_record()
    {

        $this->display('game_record');
    }
}